import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExcutorApplication {
    private static int produeTaskSleepTime = 5000;
    private static int consumeTaskSleepTime = 1000;
    private static int produceTaskMaxNumber = 20; // 最大添加到线程池中的线程数

    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(20, 40, 30,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        for (int i = 1; i < produceTaskMaxNumber; i++) {
            try {
                //创建一个任务，加入线程池
                String work = "work@ " + i;
                System.out.println("Put : " + work);
                poolExecutor.execute(new Worker(work));
                //为了便于观察，等待一段时间
                Thread.sleep(produeTaskSleepTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static class Worker implements Runnable, Serializable {
        private static final long serialVersionUID = 0;
        //需要处理的数据
        private Object workData;

        Worker(Object data) {
            this.workData = data;

        }

        public void run() {
            System.out.println("Start------" + workData);
            try {
                Thread.sleep(consumeTaskSleepTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            workData = null;
        }

        public Object getWorkData() {
            return this.workData;
        }

    }
}
